//
//  LJWBStatusListViewModel.swift
//  LJWeibo
//
//  Created by 连俊杨 on 2017/10/13.
//  Copyright © 2017年 yang_ljun. All rights reserved.
//

import Foundation

fileprivate let maxPullUpTryTimes = 3

/// 微博数据视图模型
class LJWBStatusListViewModel {
    /// 文本数据的数组
    lazy var statusList = [LJWBStatus]()
    
    fileprivate var pullUpErrorTimes = 0
    
    func loadStatus(pullUp: Bool, completion: @escaping (_ isSuccess: Bool, _ shouldRefresh: Bool)->()) {
        
        if pullUp && pullUpErrorTimes > maxPullUpTryTimes {
            
            completion(true, false)
            return
        }
        
        let since_id = pullUp ? 0 : (statusList.first?.id ?? 0)
        let max_id = !pullUp ? 0 : (statusList.last?.id ?? 0)
        
        LJNetworkManager.sharedManager.statusList(since_id: since_id, max_id: max_id) { (json, isSuccess) in
            /// 字典转模型
            guard let array = NSArray.yy_modelArray(with: LJWBStatus.self, json: json ?? []) as? [LJWBStatus] else {
                
                completion(isSuccess, false)
                return
            }
            
            print("刷新了\(array.count)条数据")
            
            if pullUp { // 上拉，添加到数组后面
                
                self.statusList += array
            }
            else {
                /// 下拉，添加到数组前面
                self.statusList = array + self.statusList
            }
            
            if pullUp && array.count == 0 {
                completion(isSuccess, false)
            }
            else {
                completion(isSuccess, true)
            }
        }
    }
}
